
//
//  SYCollectionViewLayout.m
//  SYCollectionviewTest
//
//  Created by apple on 2019/1/2.
//  Copyright © 2019 ZMX. All rights reserved.
//

#import "SYFormCollectionViewLayout.h"
@interface SYFormCollectionViewLayout (){
    NSUInteger _lineTotalItem;
    CGFloat _totalWidth;
    CGFloat _totalHeight;
}


/**      **/
@property(nonatomic, strong) NSMutableArray<NSArray<UICollectionViewLayoutAttributes *> *> *attributesArray;



@end


@implementation SYFormCollectionViewLayout

- (instancetype)init{
    self = [super init];
    if (self) {
        //        UICollectionViewFlowLayout
        
//        NSLog(@"=========  init =========");
        self.scrollDirection = SYLayoutCollectionViewScrollDirectionVertical;
        
        
    }
    return self;
}

/***  所有item的布局需要现在 prepareLayout  中布局好
prepareLayout是专门用来准备布局的，在 prepareLayout 方法里面我们可以事先就计算后面要用到的布局信息并存储起来，防止后面方法多次计算，提高性能。例如，我们可以在此方法就计算好每个cell的属性、整个CollectionView的内容尺寸等等。此方法在布局之前会调用一次，之后只有在调用 invalidateLayout 、 shouldInvalidateLayoutForBoundsChange: 返回 YES 和 UICollectionView刷新 的时候才会调用。
 一是获取对应indexPath的 UICollectionViewLayoutAttributes 对象，并存储到二维数组 layoutInfoArr 当中；
 
 二是计算出内容尺寸并保存到全局变量 contentSize 当中。
 */
-(void)prepareLayout{
    [super prepareLayout];
    
    
    
    /***  获取 n内容的 size  */
    CGSize contentSize = self.collectionViewContentSize;
    /***  计算实际可用内容宽度  */
    CGFloat availableWidth = (contentSize.width - self.contentEdgeInset.left - self.contentEdgeInset.right);
    /***  计算 尚未去除行间距的个数 一行所能容下的item个数  floor 函数向下取整  */
    _lineTotalItem = floor(availableWidth / self.itemSize.width);
    
//    availableWidth = availableWidth - _lineTotalItem * self.interItemSpacing;
//    _lineTotalItem = floor(availableWidth / self.itemSize.width);
//
//
//    /***  计算 实际间距  */
//    CGFloat newInterItemSpacing = ((contentSize.width - self.contentEdgeInset.left - self.contentEdgeInset.right) - _lineTotalItem * self.itemSize.width) / (_lineTotalItem);
//    if (newInterItemSpacing > self.interItemSpacing) {
//        self.interItemSpacing = newInterItemSpacing;
//    }
    
    
    
    _attributesArray = [NSMutableArray array];
    NSUInteger maxNumberOfRows = 0;
    
    NSUInteger numberOfSection = [self.collectionView numberOfSections];
    
    for (NSUInteger  section = 0; section < numberOfSection; section ++) {
        NSUInteger numberOfRows = [self.collectionView numberOfItemsInSection:section];
        
        NSMutableArray<UICollectionViewLayoutAttributes *> *rowItems = [NSMutableArray arrayWithCapacity:numberOfRows];
        for (NSUInteger row = 0; row < numberOfRows; row ++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
            
            UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForItemAtIndexPath:indexPath];
            [rowItems addObject:attributes];
        }
        if (maxNumberOfRows < numberOfRows) {
            maxNumberOfRows = numberOfRows;
        }
        
        [_attributesArray addObject:[rowItems mutableCopy]];
    }
    
    
    if (self.contentLayoutSize.height == 0 && self.contentLayoutSize.width == 0) {

        if (self.scrollDirection == SYLayoutCollectionViewScrollDirectionVertical) {
            CGFloat contentWidth = self.contentEdgeInset.left + self.contentEdgeInset.right + self.interItemSpacing + numberOfSection * (self.itemSize.width + self.interItemSpacing);
            
            CGFloat contentHeight = self.contentEdgeInset.top + self.contentEdgeInset.bottom + self.lineSpacing + maxNumberOfRows * (self.itemSize.height + self.lineSpacing);
            self.contentLayoutSize = CGSizeMake(contentWidth, contentHeight);
        }
        
        if (self.scrollDirection == SYLayoutCollectionViewScrollDirectionHorizontal) {
            CGFloat contentWidth = self.contentEdgeInset.left + self.contentEdgeInset.right + self.interItemSpacing + maxNumberOfRows * (self.itemSize.width + self.interItemSpacing);
            
            CGFloat contentHeight = self.contentEdgeInset.top + self.contentEdgeInset.bottom + self.lineSpacing + numberOfSection * (self.itemSize.height + self.lineSpacing);
            self.contentLayoutSize = CGSizeMake(contentWidth, contentHeight);
        }
    }
    
//    [self.attributesArray removeAllObjects];
    
    NSLog(@"======1111===  prepareLayout =========");
    
    
    
}

- (CGSize)collectionViewContentSize{
//       NSLog(@"====2222=====  collectionViewContentSize =========");
    
    return self.contentLayoutSize;
    
//    return CGSizeMake(kScreen_Size.width * 2, kScreen_Size.height * 2);
}


- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    
//    NSLog(@"======33333===  layoutAttributesForElementsInRect =========");
    
    NSMutableArray *layoutAttributesArr = [NSMutableArray array];
    [self.attributesArray enumerateObjectsUsingBlock:^(NSArray<UICollectionViewLayoutAttributes *> * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        [obj enumerateObjectsUsingBlock:^(UICollectionViewLayoutAttributes * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
                    if(CGRectIntersectsRect(obj.frame, rect)) {
                        [layoutAttributesArr addObject:obj];
                    }
        }];
        
    }];
    
    
    return layoutAttributesArr;
}


/***  返回对应于indexPath的位置的cell的布局属性,返回指定indexPath的item的布局信息。子类必须重载该方法,该方法只能为cell提供布局信息，不能为补充视图和装饰视图提供。  */

/***  局部变量记录X Y 值  */
CGFloat itemX = 0;
CGFloat itemY = 0;
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    
//    NSLog(@"=========  layoutAttributesForItemAtIndexPath =========");
     /***  每个cell 的size  */
    if (self.SYCollectionViewDelegateLayout && [self.SYCollectionViewDelegateLayout respondsToSelector:@selector(SYCollectionView:layout:sizeForItemAtIndexPath:)]) {
        
        self.itemSize = [self.SYCollectionViewDelegateLayout SYCollectionView:self.collectionView layout:self sizeForItemAtIndexPath:indexPath];
    }
    
   /***  区域m内容距离边界的距离  */
    if (self.SYCollectionViewDelegateLayout && [self.SYCollectionViewDelegateLayout respondsToSelector:@selector(SYCollectionView:layout:insetForSectionAtIndex:)]) {
        
           self.contentEdgeInset = [self.SYCollectionViewDelegateLayout SYCollectionView:self.collectionView layout:self insetForSectionAtIndex:indexPath.section];
    }

    /***  最小的行间距  */
    if (self.SYCollectionViewDelegateLayout && [self.SYCollectionViewDelegateLayout respondsToSelector:@selector(SYCollectionView:layout:minimumLineSpacingForSectionAtIndex:)]) {
          self.lineSpacing = [self.SYCollectionViewDelegateLayout SYCollectionView:self.collectionView layout:self minimumLineSpacingForSectionAtIndex:indexPath.section];
    }

    /***  最小的列间距  */

    
    if (self.SYCollectionViewDelegateLayout && [self.SYCollectionViewDelegateLayout respondsToSelector:@selector(SYCollectionView:layout:minimumInteritemSpacingForSectionAtIndex:)]) {
        self.interItemSpacing = [self.SYCollectionViewDelegateLayout SYCollectionView:self.collectionView layout:self minimumInteritemSpacingForSectionAtIndex:indexPath.section];
    }
//
    /***  获得 区域内 item 的总个数  */
//    NSInteger totalItem = [self.collectionView.dataSource collectionView:self.collectionView numberOfItemsInSection:indexPath.section];

    
    
    
    if (indexPath.section == 0 && indexPath.row == 2) {
        NSLog(@"%0.2f",self.itemSize.height);
    }
    
    if (indexPath.section == 0 ) {
        _totalWidth = self.contentEdgeInset.left;
    }
    
    if (indexPath.row == 0) {
        _totalHeight = self.contentEdgeInset.top;
    }
    
    if (indexPath.section != 0) {
        _totalWidth = self.contentEdgeInset.left + (self.itemSize.width + self.interItemSpacing) * indexPath.section;
    }
    
    if (indexPath.row != 0) {
        CGSize lastItem = [self.SYCollectionViewDelegateLayout SYCollectionView:self.collectionView layout:self sizeForItemAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row - 1 inSection:indexPath.section]];
        if (self.itemSize.height == 0) {
            _totalHeight += lastItem.height;
        }
        else{
            _totalHeight += lastItem.height + self.lineSpacing;
        }
        
    }
    
    
    itemX = _totalWidth;
    itemY = _totalHeight;
    
//    itemX = (self.interItemSpacing + self.itemSize.width) * indexPath.section;
//    itemY = (self.itemSize.height + self.lineSpacing) * indexPath.row;
    
//
//    if (indexPath.row % _lineTotalItem == 0) {
//        /***  每行第一个item 不需要添加 行间距  */
//        NSLog(@"%ld",indexPath.row);
//
//        itemX = self.contentEdgeInset.left;
//        if (indexPath.row == 0) {
//            itemY = self.contentEdgeInset.top;
//        }
//        else{
//            itemY = self.contentEdgeInset.top + (indexPath.row / _lineTotalItem * (self.itemSize.height + self.lineSpacing));
//        }
//
//    }
//    else{
//        /***  其他的item 需要添加 行间距  */
//        itemX = self.contentEdgeInset.left + (indexPath.row % _lineTotalItem) * (self.itemSize.width + self.interItemSpacing);
//    }
    
    
    NSLog(@"%f",itemY);
    CGRect itemFrame = CGRectMake(itemX, itemY, self.itemSize.width, self.itemSize.height);
    
    UICollectionViewLayoutAttributes *attributs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    attributs.frame = itemFrame;
    
    
    return attributs;
}


///返回对应于indexPath的位置的追加视图的布局属性，如果没有追加视图可不重载
-(UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    return [super layoutAttributesForSupplementaryViewOfKind:kind atIndexPath:indexPath];
}

///返回对应于indexPath的位置的装饰视图的布局属性，如果没有装饰视图可不重载
-(UICollectionViewLayoutAttributes *)layoutAttributesForDecorationViewOfKind:(NSString*)decorationViewKind atIndexPath:(NSIndexPath*)indexPath{
    return [super layoutAttributesForDecorationViewOfKind:decorationViewKind atIndexPath:indexPath];
}

///当边界发生改变时，是否应该刷新布局。如果YES则在边界变化（一般是scroll到其他地方）时，将重新计算需要的布局信息。
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
    return [super shouldInvalidateLayoutForBoundsChange:newBounds];
}

-(NSMutableArray*)attributesArray{
    if (!_attributesArray) {
        _attributesArray = [NSMutableArray array];
    }
    return _attributesArray;
}

#pragma mark === set method


//- (void)setItemSize:(CGSize)itemSize{

    
    
//}




@end
